<template>
  <div>
    <div class="mine-detail-wraper">
      <div class="mine-background-pic" @contextmenu.prevent="showChangeBG(5)">
        <el-image
          :src="
            userUrl(userInfo.backgroundImg)
              ? userUrl(userInfo.backgroundImg)
              : defalutBackgroundPic
          "
          fit="cover"
        ></el-image>
        <!-- 更换背景图片 -->
        <div class="change-bg-wrap">
          <el-upload
            :action="defalutUploadUrl"
            :show-file-list="false"
            :headers="headerObj"
            name="files"
            :on-success="bgPicUploadSuccess"
            :on-error="uploadError"
          >
            <i class="el-icon-camera-solid"></i>
          </el-upload>
        </div>
      </div>
      <div class="mine-message-wraper">
        <div class="mine-pic-name">
          <div class="mine-pic">
            <el-image
              :src="
                userUrl(userInfo.avatar)
                  ? userUrl(userInfo.avatar)
                  : defalutAvatar
              "
              fit="cover"
            ></el-image>
            <!-- 更换用户头像 -->
            <div class="change-avatar-wrap">
              <el-upload
                :action="defalutUploadUrl"
                :show-file-list="false"
                :headers="headerObj"
                name="files"
                :on-success="bgAvatatUploadSuccess"
                :on-error="uploadError"
              >
                <i class="el-icon-camera-solid"></i>
              </el-upload>
            </div>
          </div>
          <div class="mine-name">
            <div class="name">{{ userInfo.nickname }}</div>
            粉丝 <span class="fans">{{ fansNum }}</span
            >关注
            <span class="focus">{{ this.articleData[4].totalCount }}</span>
          </div>
        </div>
        <div class="mine-message">
          <div class="message showMore-wraper">
            <i class="el-icon-document icon"> </i>简介：<span>{{
              userInfo.description ? userInfo.description : "暂无简介"
            }}</span
            ><i class="el-icon-edit-outline" @click="reviseFormShow"></i>
            <i
              :class="[
                'iconfont',
                'showIcon',
                isShowMoreUserInfo
                  ? 'icon-shouqijiantouxiao'
                  : 'icon-xialajiantouxiao',
              ]"
              @click="isShowMoreUserInfo = !isShowMoreUserInfo"
            ></i>
          </div>
          <div class="message">
            <i class="icon-ip iconfont icon"></i>IP属地：<span>{{
              userInfo.ipAddress
            }}</span>
          </div>
          <div class="message" v-if="isShowMoreUserInfo">
            <i class="el-icon-date icon"></i><span>2001-8-24</span
            ><i class="el-icon-edit-outline"></i>
          </div>
          <div class="message" v-if="isShowMoreUserInfo">
            <i class="icon-riqi iconfont icon"></i
            ><span>{{ userInfo.createTime }}</span> 加入树洞
          </div>
          <div class="message" v-if="isShowMoreUserInfo">
            <i class="icon-zhanghaoquanxianguanli iconfont icon"></i>账号管理<i
              class="el-icon-edit-outline"
              @click="reviseAccountFormShow"
            ></i>
          </div>
        </div>
      </div>
      <div class="menu-wraper">
        <el-menu
          menu-trigger="click"
          active-text-color="#ff8200"
          :default-active="activeIndex"
          mode="horizontal"
          @select="selectMenuItem"
        >
          <el-menu-item index="0"><span>文章</span></el-menu-item>
          <el-menu-item index="1"><span>收藏</span></el-menu-item>
          <el-menu-item index="2"><span>分享</span></el-menu-item>

          <el-menu-item index="3"><span>点赞</span></el-menu-item>
          <el-menu-item index="4"><span>关注</span></el-menu-item>
        </el-menu>
      </div>
    </div>

    <div class="weib-num-wraper">
      <span v-if="activeIndex === '0'"
        >全部微博（{{ this.articleData[index].totalCount }}）</span
      >
      <span v-else-if="activeIndex === '1'"
        >全部收藏（{{ this.articleData[index].totalCount }}）</span
      >
      <span v-else-if="activeIndex === '2'"
        >全部分享（{{ this.articleData[index].totalCount }}）</span
      >
      <span v-else-if="activeIndex === '3'"
        >全部点赞（{{ this.articleData[index].totalCount }}）</span
      >
      <span v-else-if="activeIndex === '4'"
        >全部关注（{{ this.articleData[index].totalCount }}）</span
      >
    </div>

    <div class="mine-detail-content">
      <articleDetailList
        :articleList="this.articleData[index].list"
        @operateArticle="operateArticle"
        @focusArticle="focusArticle"
        @giveComment="giveComment"
        @deleteArticle="deleteArticle"
        @updateArticle="updateArticle"
        :parentComponent="0"
        v-if="activeIndex != '4'"
      ></articleDetailList>
      <focusAccountList
        v-else-if="activeIndex === '4'"
        :focusList="this.articleData[index].list"
      ></focusAccountList>
    </div>

    <!-- 修改用户信息对话框(简介) -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="reviseInfoDialogFormVisible"
      @close="reviseDialogClosed"
    >
      <el-form :model="reviseForm" :rules="reviseFormRules" ref="reviseFormRef">
        <el-form-item
          label="简介"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input
            v-model="reviseForm.description"
            autocomplete="off"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12"
            ><div class="reset-wrap" @click="resetUserInfo">
              <div class="reset">重置</div>
            </div></el-col
          ><el-col :span="12"
            ><div class="login-wrap" @click="reviseUserInfo">
              <div class="login">保存</div>
            </div></el-col
          ></el-row
        >
      </div>
    </el-dialog>

    <!-- 修改用户账号对话框(简介) -->
    <el-dialog
      title="修改用户账号"
      :visible.sync="reviseAccountDialogFormVisible"
      @close="reviseAccountDialogClosed"
    >
      <el-form
        :model="reviseAccountForm"
        :rules="reviseAccountFormRules"
        ref="reviseAccountFormRef"
      >
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          prop="nickname"
        >
          <el-input
            v-model="reviseAccountForm.nickname"
            autocomplete="off"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="reviseAccountForm.password"
            autocomplete="off"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="formLabelWidth"
          prop="password2"
        >
          <el-input
            v-model="reviseAccountForm.password2"
            autocomplete="off"
            show-password
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12"
            ><div class="reset-wrap" @click="resetUserAccount">
              <div class="reset">重置</div>
            </div></el-col
          ><el-col :span="12"
            ><div class="login-wrap" @click="reviseUserAccount">
              <div class="login">保存</div>
            </div></el-col
          ></el-row
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import articleDetailList from "../components/articledetail/ArticleDetailList.vue";
import focusAccountList from "../components/focus/FocusAccountList.vue";
import { mapState, mapMutations, mapActions } from "vuex";
import config from "@/config/index";
export default {
  components: {
    articleDetailList,
    focusAccountList,
  },
  created() {
    // 获取用户信息
    this.getUserInfo();
    // 获取文章信息
    this.getArticle();
    // 获取关注博主个数
    this.getFocus(2);
    // 获取粉丝个数
    this.getFocus(3);
  },
  data() {
    // 验证只能是数字和字母
    var validNumLetter = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,10}$/;
      if (!reg.test(value)) {
        callback(new Error("必须是由4-10位字母+数字组合"));
      } else {
        callback();
      }
    };
    // 验证两次密码是否一致
    var checkPasswordSave = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      }
      if (
        this.reviseAccountForm.password === this.reviseAccountForm.password2
      ) {
        return callback();
      }
      callback(new Error("请输入一致的密码"));
    };
    return {
      // 左侧文本的宽度
      formLabelWidth: "100px",
      //   图片上传组件headers请求头对象
      headerObj: {
        Authorization:
          localStorage.token_type + " " + localStorage.access_token,
      },
      // 默认头像
      defalutAvatar: config.defalutAvatar,
      // 图片展示失败默认图片
      defalutPic: config.defalutPic,
      // 默认背景图片
      defalutBackgroundPic: config.defalutBackgroundPic,
      // 默认文件上传地址
      defalutUploadUrl: config.defalutUploadUrl,
      // 粉丝个数
      fansNum: 0,
      // 查询参数
      queryInfo: [
        // 全部微博
        {
          page: 1,
          limit: 50,
        },
        // 收藏列表
        { page: 1, limit: 50 },
        // 分享列表
        { page: 1, limit: 50 },
        // 点赞列表
        { page: 1, limit: 50 },
        // 关注列表
        { page: 1, limit: 50, action: "info" },
      ],
      // 数据展示
      articleData: [
        // 全部微博数据
        {
          totalCount: 0,
          list: [],
          isAll: false,
        },
        // 收藏数据
        {
          totalCount: 0,
          list: [],
          isAll: false,
        },
        // 分享数据
        {
          totalCount: 0,
          list: [],
          isAll: false,
        },
        // 点赞数据
        {
          totalCount: 0,
          list: [],
          isAll: false,
        },

        // 关注数据
        {
          totalCount: 0,
          list: [],
          isAll: false,
        },
      ],
      // 查询地址
      queryUrl: [
        "/api/user/tweet",
        "/api/user/collection",
        "/api/user/share",
        "/api/user/like",
        "/api/user/relation",
      ],
      isShowMoreUserInfo: false,
      activeIndex: "0",
      // 修改用户的信息表单
      reviseForm: {
        description: "",
      },
      // 修改用户表单的验证规则
      reviseFormRules: {
        description: [
          { required: true, message: "请输入简介", trigger: "blur" },
        ],
      },
      // 修改用户信息对话框显示
      reviseInfoDialogFormVisible: false,

      // 修改用户账号的表单
      reviseAccountForm: {
        nickname: "",
        password: "",
        password2: "",
      },
      // 修改用户表单的验证规则
      reviseAccountFormRules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户昵称长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validNumLetter, trigger: "blur" },
        ],
        password2: [
          { required: true, message: "两次密码不一致", trigger: "blur" },
          { validator: checkPasswordSave, trigger: "blur" },
        ],
      },
      // 修改用户信息对话框显示
      reviseAccountDialogFormVisible: false,
    };
  },
  computed: {
    ...mapState("m_user", ["userInfo"]),
    index() {
      return Number(this.activeIndex);
    },
  },
  methods: {
    ...mapMutations("m_user", ["UPDATE_USER_INFO"]),
    // 用户的头像
    userUrl(userUrl) {
      if (!userUrl) return null;
      // 用户的头像加地址前缀
      return config.defalutBaseURLPic + userUrl;
    },
    // 获取用户信息
    async getUserInfo() {
      const { code, msg, result } = await this.$http.get(
        "/api/user/user_info/" + localStorage.user_id || ""
      );
      console.log(result);
      if (code != 200) {
        return this.$showMsg({
          msg: "获取用户信息失败！",
          type: "error",
        });
      }

      // 获取用户ip属地
      const res = await this.$http.get("/api/tool/get_ip");
      let code1 = res.code;
      let result1 = res.result;
      if (code1 != 200) {
        return this.$showMsg({
          msg: "获取ip属地失败！",
          type: "error",
        });
      }

      // 添加ip属地
      result.ipAddress = result1.address;
      this.UPDATE_USER_INFO(result);

      console.log(this.userInfo);
      return this.$showMsg({
        msg: "获取用户信息成功！",
        type: "success",
      });
    },
    // 获取微博数据（全部、点赞、分享、收藏）
    async getArticle() {
      let index = this.index;
      let queryInfo = this.queryInfo[index];
      let url = this.queryUrl[index];
      console.log(index, queryInfo, url);
      const { code, msg, result } = await this.$http.get(url, {
        params: queryInfo,
      });
      if (code != 200) {
        return this.$showMsg({ msg: "获取文章数据列表失败！", type: "error" });
      }
      console.log(result, "00000000000000");
      if (result.totalCount == 0) {
        this.articleData[index].totalCount = 0;
        // 数据为空
        return;
      }
      let articleList = result.list;
      this.articleData[index].totalCount = result.totalCount;

      // 获取文章是否被该用户点赞
      let articleIdList = articleList.map((v) => v.id);
      let result1 = await this.$http({
        url: "/api/tweet/user_action_status",
        type: "get",
        params: { aid: articleIdList },
      });
      if (result1.code != 200) {
        result1 = await this.$http({
          url: "/api/tweet/user_action_status",
          type: "get",
          params: { aid: articleIdList },
        });
      }
      console.log(result1.result, "给文章添加点赞 收藏 分享 数据");
      //  给文章添加点赞 收藏 分享 数据
      result1.result.forEach((v, i) => {
        articleList[i].collection = v.collection;
        articleList[i].like = v.like;
        articleList[i].share = v.share;
        articleList[i].focus = v.relation;
      });
      this.articleData[index].list = [
        ...this.articleData[index].list,
        ...articleList,
      ];
      console.log(this.articleData[index].list, articleList);
    },
    // 获取关注博主数据
    async getFocus(cateIndex = 1) {
      let index = this.index;
      if (cateIndex == 1) {
        // 正常数据
        this.queryInfo[index].action = "info";
      } else if (cateIndex == 2) {
        // 获取关注数量
        index = 4;
        this.queryInfo[index].action = "info";
      } else if (cateIndex == 3) {
        // 获取粉丝数量
        index = 4;
        this.queryInfo[index].action = "fans";
      }
      let queryInfo = this.queryInfo[index];
      let url = this.queryUrl[index];
      console.log(index, queryInfo, url);
      const { code, msg, result } = await this.$http.get(url, {
        params: queryInfo,
      });
      if (code != 200) {
        return this.$showMsg({ msg: "获取关注数据列表失败！", type: "error" });
      }
      console.log(result, "00000000000000");
      if (result.totalCount == 0) {
        this.articleData[index].totalCount = 0;
        // 数据为空
        return;
      }
      if (cateIndex == 3) {
        // 粉丝数
        this.fansNum = result.totalCount;
        return;
      } else if (cateIndex == 2) {
        this.articleData[index].totalCount = result.totalCount;
        return;
      }
      result.list.forEach((v) => (v.isFoucs = true));
      this.articleData[index].list = result.list;
      this.articleData[index].totalCount = result.totalCount;
    },

    // 点赞 收藏 分享 操作文章
    operateArticle(method, type, id) {
      // 更新点赞、收藏、关注
      let index = this.articleData[this.index].list.findIndex(
        (v) => v.id == id
      );
      this.articleData[this.index].list[index][type] =
        !this.articleData[this.index].list[index][type];
      // 更新点赞、收藏、关注数量
      let num = 1;
      if (method == "add") {
        num = 1;
      } else {
        num = -1;
      }
      if (type == "like") {
        this.articleData[this.index].list[index]["likeCount"] += num;
      } else if (type == "collection ") {
        this.articleData[this.index].list[index]["collectionCount"] += num;
      }
      return this.$showMsg({ msg: "操作成功！", type: "success" });
    },

    // 关注、取消关注博主
    focusArticle(userId) {
      this.articleData[this.index].list.forEach((v) => {
        if (v.userId == userId) {
          v.focus = !v.focus;
        }
      });
    },

    // 添加评论
    giveComment(commentForm) {
      console.log("添加评论");
    },

    // 选择菜单事件
    selectMenuItem(index, path) {
      this.activeIndex = index;
      this.articleData[index].list = [];
      if (index < 4) {
        // 获取文章数据
        this.getArticle();
      } else if (index == 4) {
        // 获取关注数据列表
        this.getFocus();
      }
    },

    // 更换头像
    async bgAvatatUploadSuccess(response, file, fileList) {
      console.log(response.result[0]);

      let userInfo = this.userInfo;
      userInfo.avatar = response.result[0];

      // 更新用户信息
      this.UPDATE_USER_INFO(userInfo);
      this.updateUserInfo();
    },

    // 更换背景图
    bgPicUploadSuccess(response, file, fileList) {
      // console.log(response.result[0]);
      let userInfo = this.userInfo;
      userInfo.backgroundImg = response.result[0];

      // 更新用户信息
      this.UPDATE_USER_INFO(userInfo);
      this.updateUserInfo();
    },

    // 文件上传失败
    uploadError(err, file, fileList) {
      return this.$showMsg({ msg: "文件上传失败!", type: "error" });
    },

    // 更新用户信息
    async updateUserInfo() {
      const { code, msg, result } = await this.$http.post(
        "/api/user/update",
        this.userInfo
      );
      console.log(msg);
      if (code != 200) {
        this.$showMsg({ type: "error", msg: "更新用户信息失败！" });
      }
      return code;
    },

    // 修改用户信息(发送请求)
    reviseUserInfo() {
      this.$refs.reviseFormRef.validate(async (valid) => {
        if (!valid) return;
        // 本地更新数据
        let userInfo = this.userInfo;
        userInfo.description = this.reviseForm.description;
        // 更新用户信息
        this.UPDATE_USER_INFO(userInfo);
        // 发起网络请求保存
        const code = await this.updateUserInfo();
        if (code != 200) {
          return;
        }
        this.reviseInfoDialogFormVisible = false;
      });
    },

    // 显示修改用户信息对话框
    reviseFormShow() {
      this.reviseForm.description = this.userInfo.description;
      this.reviseInfoDialogFormVisible = true;
    },

    // 重置表单
    resetUserInfo() {
      this.$refs.reviseFormRef.resetFields();
    },

    // 修改用户信息对话框关闭事件
    reviseDialogClosed() {
      this.$refs.reviseFormRef.resetFields();
    },

    // 修改用户账号(发送请求)
    reviseUserAccount() {
      this.$refs.reviseFormRef.validate(async (valid) => {
        if (!valid) return;
        // 本地更新数据
        let userInfo = this.userInfo;
        userInfo.description = this.reviseForm.description;
        // 更新用户信息
        this.UPDATE_USER_INFO(userInfo);
        // 发起网络请求保存
        const code = await this.updateUserInfo();
        if (code != 200) {
          return;
        }
        this.reviseAccountDialogFormVisible = false;
      });
    },

    // 显示修改用户账号对话框
    reviseAccountFormShow() {
      this.reviseAccountForm.nickname = this.userInfo.nickname;
      this.reviseAccountDialogFormVisible = true;
    },

    // 重置账号表单
    resetUserAccount() {
      console.log("ff");
      this.$refs.reviseAccountFormRef.resetFields();
    },

    // 修改用户账号对话框关闭事件
    reviseAccountDialogClosed() {
      this.$refs.reviseAccountFormRef.resetFields();
    },

    // 删除文章
    deleteArticle(articleItem) {
      let index = this.articleData[this.index].list.findIndex(
        (v) => v.id == articleItem.id
      );
      // console.log(index);
      this.articleData[this.index].list.splice(index, 1);
    },

    // 更新文章数据
    updateArticle(editArticleForm, articleId) {
      console.log(editArticleForm, articleId);
      let index = this.articleData[this.index].list.findIndex(
        (v) => v.id == articleId
      );
      // console.log(index);
      let articleItem = this.articleData[this.index].list[index];
      for (let item in editArticleForm) {
        articleItem[item] = editArticleForm[item] ? 1 : 0;
      }
      this.articleData[this.index].list[index] = articleItem;
    },
  },
};
</script>

<style scoped lang="less">
.mine-detail-wraper {
  background-color: white;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 4px;
  .mine-background-pic {
    &:hover .change-bg-wrap {
      visibility: visible;
    }
    position: relative;
    .el-image {
      width: 100%;
      max-height: 300px;
      filter: blur(2px);
    }
    .change-bg-wrap {
      position: absolute;
      bottom: 5px;
      right: 50px;
      visibility: hidden;
      .el-icon-camera-solid {
        font-size: 26px;
        color: #ff8200;
      }
    }
  }
  .mine-message-wraper {
    margin-left: 20px;
    margin-bottom: 20px;
    .mine-pic-name {
      display: flex;
      .mine-pic {
        position: relative;
        &:hover .change-avatar-wrap {
          visibility: visible;
        }
        .el-image {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          margin-top: -45px;
          border: 2px white solid;
        }
        .change-avatar-wrap {
          width: 20px;
          height: 20px;
          position: absolute;
          top: 50%;
          left: 50%;
          margin-left: -15px;
          margin-top: -20px;
          visibility: hidden;
          .el-icon-camera-solid {
            font-size: 26px;
            color: #ff8200;
          }
        }
      }
      .mine-name {
        color: #939393;
        font-size: 14px;
        margin: 0 10px;
        text-align: left;
        .name {
          font-size: 18px;
          color: #333;
          font-weight: 650;
          margin-bottom: 5px;
        }
        .fans {
          margin-right: 10px;
          color: #333;
          font-size: 14px;
        }
        .focus {
          color: #333;
          font-size: 14px;
        }
      }
    }

    .mine-message {
      &:hover .message .el-icon-edit-outline {
        visibility: visible;
      }
      color: #939393;
      font-size: 14px;
      margin-left: 10px;
      .message {
        text-align: left;
        margin-top: 12px;
        .icon {
          margin-right: 8px;
        }
        .el-icon-edit-outline {
          margin-left: 10px;
          visibility: hidden;
          cursor: pointer;
        }
      }
      .showMore-wraper {
        position: relative;
        .showIcon {
          position: absolute;
          right: 100px;
          font-size: 20px;
          color: #ff8200;
          cursor: pointer;
        }
      }
    }
  }
  .menu-wraper {
    width: 100%;
    border-top: rgb(230, 230, 230) 1px solid;
    .el-menu {
      .el-menu-item {
        width: 20%;
        font-size: 18px;
        color: #333;
      }
    }
  }
}

.weib-num-wraper {
  text-align: left;
  font-size: 16px;
  color: #333;
  padding-top: 10px;
}

.mine-detail-content {
  margin-top: 10px;
}

.dialog-footer {
  .login-wrap {
    width: 100%;
    color: white;
    display: flex;
    justify-content: center;
    font-weight: 540;
    .login {
      width: 120px;
      background-color: #ffa00a;
      text-align: center;
      height: 40px;
      line-height: 40px;
      cursor: pointer;
      border-radius: 10px;
    }
  }
  .reset-wrap {
    width: 100%;
    font-weight: 550;
    display: flex;
    justify-content: center;
    .reset {
      height: 40px;
      line-height: 40px;
      cursor: pointer;
      color: #939393;
    }
  }
}
</style>